
var BroadcastListView = View.extend(BroadcastListView = {
    
    filterCount: 0,
    
    init: function() {
        this.configureUI();
    },
    configureUI: function() {
        var self = this;
        
        this.configureNewListAction();

        $(".broadcast-list-item").click( function( e ) {
            e.preventDefault();
            
            self.loadBroadcastListEditor(this);
        });
        
        $(".broadcast_list_preview").click( function( e ) {
            e.preventDefault();
            
            self.previewContacts(this);
        });
        
        $(".broadcast_list_delete").click(function() {
            var id = $(this).data('id');
            
            confirm('You are about to delete this broadcast list and all related data. Are you sure you want to continue?', function() {
                self.deleteList(id);
            });
        });
    },
    
    loadBroadcastListEditor: function(trigger) {
        var self = this;
        var $this = $(trigger);
        var url = $(trigger).attr('href');

        $("#broadcast-list-contacts #instruction").hide();
        $("#broadcast-list-contacts #editor").html('Loading ....');

        $.ajax({
            url: url,
            type: 'get',
            success: function( response ) {
                $("#broadcast-list-contacts #editor").html(response);
                
                self.setupEditorUI();

                $this.parents("li").addClass('selected');
            },
            error: function( xhr ) {
                $("#broadcast-list-contacts #editor").html(xhr.responseText);
            }
        });
    },
    
    configureNewListAction: function() {
        var self = this;

        $("#new_list").click(function( e ) {
            e.preventDefault();
            var url = $(this).attr('href');

            $("#broadcast-list-contacts #instruction").hide();
            $("#broadcast-list-contacts").html("Loading List Editor ...");
            
            $.get(url, function( res ) {
                $("#broadcast-list-contacts").html(res);
                self.addFilter('required');
            });
        });
        
        $(document).on('click', '#add_filter_btn li a', function() {
            self.addFilter( $(this).attr('id') );
        });
        
        $(document).on('click', '.filter-remove', function() {
            self.removeFilter(this);
        });
        
        $(document).on('submit', "#list_form", function(e) {
            e.preventDefault();
            self.submitForm();
        });
        
        App.listen('filtersUpdated', function() {
            var sample = self.buildFilterQuerySample();
            $("#filter_query_sample").html( sample );
        });
        
        this.setupNewListUI();
    },
    
    addFilter: function(type) {
        var filter = $("#filter-template").html();
        
        if( filter ) {
            filter = filter.replace(/\{d\}/g, this.filterCount++);
            filter = filter.replace(/\{optional\}/g, type == 'required' ? '0' : '1');
            
            if( type == 'required' ) {
                $("#filter-group .required").append(filter);
            }
            else if( type == 'optional' ) {
                $("#filter-group .optional").append(filter);
            }
            
        }
    },
    
    removeFilter: function(trigger) {
        var id = $(trigger).siblings('.filter-id').val();
        var self = this;
        
        if( id ) {
            confirm("Are you sure you want to delete this filter?", function() {
                var url = $("#remove_filter_url").val();
                var params = {filter_id: id};

                $.get(url, params, function(res) {
                    if( res.status == 'success' ) {
                        $(trigger).parents('.filter').remove();
                        App.notify('filtersUpdated');
                    }
                }, 'json');
            });
        }
        
        else {
            $(trigger).parents('.filter').remove();
            App.notify('filtersUpdated');
        }
    },
    
    setupEditorUI: function() {
        var self = this;
        
        if( typeof filter_data != 'undefined' ) {
            if( filter_data.length > 0 ) {
                for(var i = 0; i < filter_data.length; i++) {
                    var filter = filter_data[i];
                    var group = filter['optional'] == 1 ? 'optional' : 'required';
                    self.addFilter( group );

                    $("." + group + " .filter:last-child .filter-field").val( filter['field'] ).change();
                    $("." + group + " .filter:last-child .filter-conditions").val( filter['condition'] );
                    $("." + group + " .filter:last-child .filter-value").val( filter['value'] );
                    $("." + group + " .filter:last-child .filter-id").val( filter['id'] );
                    $("." + group + " .filter:last-child .filter-optional").val( filter['optional'] ? '1' : '0' );
                }
            }
        }
        
        $("#list_form_submit").html("<i class='fa fa-save'></i> Save Changes");
        
        $("#preview_list_btn").click(function(e) {
            e.preventDefault();
            
            self.previewContacts(this);
        });
        
        App.notify('filtersUpdated');
    },
    
    previewContacts: function(trigger) {
        var self = this;
        
        $("#broadcast-list-contacts #instruction").hide();
        $("#broadcast-list-contacts #editor").html("Loading Contacts List Preview ...");
            
        $.get( $(trigger).attr('href'), function(res) {
            $("#broadcast-list-contacts #editor").html(res);

            $("#edit_list_btn").click(function(e) {
                e.preventDefault();

                self.loadBroadcastListEditor(this);
            });
        });
    },
    
    filters: function() {
        return {
            'Member Profile': {
                'Member Category': {
                    conditions: ['='],
                    select: category_select
                },
                'Name': {
                    conditions: ['=', '{s}%', '%{s}', '%{s}%'],
                    select: false
                },
                'Gender': {
                    conditions: ['='],
                    select: {male: 'Male', female: 'Female'}
                },
                'Marital Status': {
                    conditions: ['='],
                    select: {
                        single: 'Single', married: 'Married', 
                        cohabiting: 'Cohabiting', divorced: 'Divorced',
                        widowed: 'Widowed'
                    }
                },
                'Age': {
                    conditions: ['=', '>=', '>', '<', '<='],
                    select: false
                },
                'Birth Month': {
                    conditions: ['='],
                    select: {
                        January: 'January', February: 'February', March: 'March', April: 'April', May: 'May', June: 'June',
                        July: 'July', August: 'August', September: 'September', October: 'October', November: 'November', December: 'December'
                    }
                },
                'Birth Day Of Week': {
                    conditions: ['='],
                    select: {
                        Sunday: 'Sunday', Monday: 'Monday', Tuesday: 'Tuesday', Wednesday: 'Wednesday',
                        Thursday: 'Thursday', Friday: 'Friday', Saturday: 'Saturday'
                    }
                },
                'Occupation': {
                    conditions: ['=', '{s}%', '%{s}', '%{s}%'],
                    select: false
                },
                'Email': {
                    conditions: ['=', '{s}%', '%{s}', '%{s}%'],
                    select: false
                },
                'Phone Number': {
                    conditions: ['=', '{s}%', '%{s}', '%{s}%'],
                    select: false
                }
            },
            'Groups': {
                '*': {
                    conditions: ['='],
                    select: {
                        
                    }
                }
            }
        };
    },
    
    setupNewListUI: function() {
        var self = this;
        
        $(document).on('keypress', '#sender_id', function(event){
            var txt = String.fromCharCode(event.which);
            
            if ((event.which == 97) && (event.ctrlKey || event.metaKey)) {
                // Allow CTRL-A and Command-A (select all)
                return true;
            } else if ($.inArray(event.which, [0, 8, 9, 114]) != -1) {
                // Allow backspace and tab
                return true;
            } else if(!txt.match(/^[A-Za-z0-9]+$/)) {
                return false;
            }
        });
        
        $(document).on('change', '.filter-field', function() {
            var $conditions = $(this).next('select.filter-conditions');
            var $select = $(this).siblings('select.filter-value');
            var $input = $(this).siblings('input.filter-value');
            
            var option = this.options[this.selectedIndex];
            var group = $(option).parent().attr('label');
            var text = option.text;
            
            try {
                var filter = null;
                if( group == 'Member Profile') {
                    filter = self.filters()[group][text];
                }

                else {
                    filter = self.filters()['Groups']['*'];
                    filter.select = group_select[$(option).data('type-id')];
                }

                if( filter ) {
                    if( filter.select == false ) {
                        $select.attr('disabled',true).val('').hide();
                        $input.removeAttr('disabled').show();
                    }

                    else {
                        $select.find('option').remove();
                        $select.append($('<option />').val('').html('Select Option'));

                        for(var key in filter.select) {
                            $("<option />").attr('value', key).html( filter.select[key] ).appendTo($select);
                        }

                        $select.removeAttr('disabled').show();
                        $input.attr('disabled',true).val('').hide();
                    }

                    if( filter.conditions ) {
                        $conditions.find('option').addClass('hidden');

                        for(var i = 0; i < filter.conditions.length; i++) {
                            var cond = filter.conditions[i];
                            $conditions.find('option').each(function() {
                                if( $(this).attr('value') == cond ) {
                                    $(this).removeClass('hidden').addClass('visible');
                                }
                            });
                        }

                        if( filter.conditions.length == 1 ) {
                            $conditions.val( filter.conditions[0] );
                        }

                        else {
                            $conditions.find('option').eq(0).removeClass('hidden');
                            $conditions.val('');
                        }
                    }
                }
            } catch(e) {
                console.log(e);
            }
        });
        
        $(document).on('change', '.filter-value', function() {
            var query = self.buildFilterQuerySample();
            
            $("#filter_query_sample").html(query);
        });
    },
    
    buildFilterQuerySample: function() {
        var required = [], optional = [];
        
        $(".filter-field").each(function() {
            var $conditions = $(this).next('select.filter-conditions');
            var $select = $(this).siblings('select.filter-value');
            var $input = $(this).siblings('input.filter-value');
            
            var q = null;
                
            switch( $conditions.val() ) {
                case '=':
                case '>=':
                case '>':
                case '<':
                case '<=':
                    var value = $select.val() != '' ? $select.find('option:selected').text() : $input.val();
                    q = "`" + $(this).find('option:selected').text() + "` " + $conditions.val() + " <b>'" + value + "'</b> ";        
                    break;
                case '%{s}':
                case '{s}%':
                case '%{s}%':
                    var val_text = $select.val() != '' ? $select.find('option:selected').text() : $input.val();
                    var cond = $conditions.val();
                    var val = cond.replace(/\{s\}/g, val_text);
                    q = "`" + $(this).find('option:selected').text() + "` LIKE <b>'" + val + "'</b> ";
                    break;
            }
            
            if( $(this).parents('.group').hasClass('required') ) {
                required.push(q);
            }
            else {
                optional.push(q);
            }
        });
        
        var query = required.join(' AND '); 
        
        if( optional.length > 0 ) {
            if( query != '' ) {
                query = "(" + query + ") AND (" + optional.join(' OR ') + ")";
            }
            else {
                query = optional.join(' OR ');
            }
        }
        
        return query;
    },
    
    submitForm: function() {
        var url = $('#list_form').attr('action');
        var params = $("#list_form").serialize();
        
        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function( response ) {
                if( response.status == 'success' ) {
                    alert('New List Created Successfully');
                    window.history.go(0);
                }
                
                else {
                    alert('Failed to save changes to broadcast list. Please try again.');
                }
            },
            error: function( xhr ) {
                console.log(xhr.responseText);
                alert("Failed to save changes to this form. Please try again.");
            }
        });
    },
    
    deleteList: function(id) {
        var url = $("#remove_list_url").val();
        var params = {broadcast_list_id: id};
        
        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function( response ) {
                if( response.status == 'success' ) {
                    $(".broadcast_list_delete").each(function() {
                        if( $(this).data('id') == id ) {
                            $(this).parents('tr').remove();
                        } 
                    });
                    
                    $("#broadcast-list-contacts #editor").html("");
                    $("#broadcast-list-contacts #instruction").show();
                }
                
                else {
                    alert(response.message);
                }
            },
            error: function( xhr ) {
                alert('Failed to remove broadcast list due to server side error. Please try again');
            }
        });
    }
});

$(document).ready(function() {
    var view = new BroadcastListView();
});
